<!-- 附件信息 -->
<template>
  <div ref="attachmentListRef" class="attachmentList">
    <div v-if="['A','C'].includes(prjParams.btnConfig)" style="padding: 10px;color: #D9001B;">
      <span>需上传附件（必传）：</span>
      <span>{{ prjFileTypeOption | prjFileType }}</span>
    </div>
    <MyTable
      id="fileId"
      ref="myTableRef"
      :is-mar-class="true"
      :table-data="tableData"
      :columns="columnEnum[prjParams.btnConfig]"
      :table-operation="btnEnum[prjParams.btnConfig]"
      :col-option-enum="dicLists"
      @propClick="btnClick"
    >
      <template #headerLeft>
        <el-form :model="tableForm" label-width="100px" class="pms-details" size="mini" :disabled="false" :inline="true">
          <el-form-item label="项目阶段">
            <el-select
                v-model="tableForm.prjStage"
                clearable
                :popper-append-to-body="false"
                placeholder="请选择"
                @change="changePrjPhase"
            >
              <el-option
                  v-for="item in dicLists['PRO_STAGE']"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目节点">
            <el-select v-model="tableForm.nodeId" clearable :popper-append-to-body="false" placeholder="请选择" @change="changePrjNode">
              <el-option
                  v-for="item in dicLists['ATT_PRO_NODE']"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目编码" v-if="selectArray.length > 0 && +prjParams.showPrjCode === 1">
            <el-select v-model="tableForm.prjCode" clearable placeholder="请选择" :popper-append-to-body="false" @change="changePrjCode">
              <el-option
                  v-for="item in selectArray"
                  :key="item.prjId"
                  :label="item.prjCode"
                  :value="item.prjCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #docTypeName="{ scope }">
        <span v-if="+scope.isMust === 1" style="color: red">*</span>
        <span>{{ scope.docTypeName }}</span>
      </template>
      <template #fileName="{ scope }">
        <el-button type="text" @click="preview(scope)">
          {{ scope.fileName }}
        </el-button>
      </template>
    </MyTable>
    <pagination
      v-if="pageParam.total > 10"
      :total="pageParam.total"
      :page.sync="pageParam.pageNum"
      :limit.sync="pageParam.pageSize"
      @pagination="doSearch"
    />
    <!-- 指派签署人-->
    <el-dialog
      v-if="dialogUpload"
      ref="dialogUploadRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :modal="true"
      :title="dialogTitle"
      width="50%"
      class="pms-zr-dialog"
      :visible.sync="dialogUpload"
      @close="() => { isShowStampUnit = false; dialogClosed() }"
    >
      <!-- @touchmove.prevent -->
      <div class="signatoryBody">
        <ChooseSignatory
          v-if="isShowStampUnit"
          ref="chooseSignatoryRef"
          class="signatoryClass"
          :prj-data="prjData"
        >
          <template #remarks>
            <Signatory :is-signatory="!isUploadBtn" />
          </template>
        </ChooseSignatory>
      </div>
      <div slot="footer" class="pms-zr-dialog-footer">
        <el-button class="pms-zr-button-primary" size="small" :disabled="assignDisable" v-debounce="assignSignatorysubmit">
          提 交
        </el-button>
        <el-button
          class="pms-zr-button-primary pms-zr-ClosedBtn"
          size="small"
          @click="() => { dialogUpload = false; isShowStampUnit = false; dialogClosed() }"
        >
          取 消
        </el-button>
      </div>
    </el-dialog>
    <!-- 上传附件 -->
    <el-dialog
      v-if="dialogUploadNew"
      ref="dialogUploadNewRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :modal="true"
      :title="dialogTitle"
      width="50%"
      class="pms-zr-dialog"
      :visible.sync="dialogUploadNew"
      @close="() => { dialogUploadClosed() }"
    >
      <div style="max-height: 620px;overflow-y: auto;overflow-x: hidden;border: 1px solid #aaa;">
        <UploadAttach
          v-if="isUploadBtn"
          ref="uploadAttachRef"
          :prj-params="prjParams"
          :select-array="selectArray"
          :prj-file-type-option="prjFileTypeOption"
        />
      </div>
      <div slot="footer" class="pms-zr-dialog-footer">
        <el-button class="pms-zr-button-primary" size="small" v-debounce="startUpload">
          开始上传
        </el-button>
        <el-button
          class="pms-zr-button-primary pms-zr-ClosedBtn"
          size="small"
          @click="() => { dialogUploadClosed() }"
        >
          关 闭
        </el-button>
      </div>
    </el-dialog>
    <!-- 文件预览 -->
    <el-dialog
      v-if="dialogFileView"
      ref="dialogViewRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      :lock-scroll="true"
      title="预览"
      height="60%"
      width="60%"
      class="pms-zr-dialog"
      :visible.sync="dialogFileView"
      @close="dialogClosed"
    >
      <div class="signatoryPre">
        <FilePreview ref="filePreviewRef" class="filePreviewClass" :file-obj="fileObj" />
      </div>
      <div slot="footer" class="pms-zr-dialog-footer">
        <el-button
          class="pms-zr-button-primary"
          style="background-color: #eb4b4b; color: #fff;"
          size="small"
          @click="() => { dialogFileView = false; dialogClosed() }"
        >
          取 消
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog
      v-if="dialogEdit"
      ref="dialogEditRef"
      v-dialogDrag
      :append-to-body="true"
      :modal-append-to-body="true"
      :modal="true"
      :close-on-click-modal="false"
      :lock-scroll="true"
      :title="dialogEditTitle"
      width="70%"
      class="pms-zr-dialog"
      :visible.sync="dialogEdit"
      @close="editClose"
    >
      <div ref="signatoryPreRef" class="signatoryPre" style="height: 62vh;">
        <iframe
          ref="myIframeFjRef"
          title="iframeFjRef"
          width="100%"
          height="99%"
          style="overflow:hidden;border: none;"
          :src="editSrc"
        />
        <!-- :height="iframeHeight" -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import MyTable from '@/components/basic/myTable'
import Signatory from './signatory'
import ChooseSignatory from './chooseSignatory'
import UploadAttach from './uploadAttach'
import FilePreview from '@/components/business/filePreview.vue'
import SysConst from '@/common/const'
import { colOptionA, colOptionB, btnOptionA, btnOptionB, btnOptionC, btnOptionD, btnOptionE, btnOptionF } from '.'
import { getDropdownData } from '@/api/common' // 字典接口
import { getQueryObject, disableScroll, enableScroll, msgInfoEl, downloadFileFun } from '@/utils' // singleDownload, mulDownload,
import { getNodeInfoApi } from '@/api/attachManagement/attachments/attachmentDetails'
import { getSignFlowDocUrlsApi } from '@/api/attachManagement/electronicSign/electronicSignature'
import {
  queryDocInfo,
  uploadSignInfoApi, // 电子签章上传
  assignSignatoryApi, // 电子签章指派签署人
  batchDeleteApi,
  getPrjStageApi,
  acceGenerationElectron,
  batchDownloadApi, // 批量下载
  downloadApi,
  getPrjFileTypeApi,
  queryBuildModesApi,
  getDigitalDrawingsUrl,
  getWPSToken,
  getPreviewFile,
  checkFileEditing,
  querySingleInfo,
  querySuffix,  // 单个文件下载
} from '@/api/attachmentInfo'
import $ from 'jquery'

const Base64 = require('js-base64').Base64

export default {
    name: 'AttachmentList',
    components: {
        MyTable,
        Signatory,
        ChooseSignatory,
        UploadAttach,
        FilePreview
    },
    filters: {
        prjFileType(data) {
            if (!data.length) {
              return ''
            } else {
            const list = data.filter((item) => item.isMust === '1')
            const filterList = list.map(item => item.typeName)
            const customCheck = filterList.join().replaceAll(',', '、')
            return customCheck
            }
        }
    },
    data() {
        return {
            tableData: [], // 附件列表数据
            prjFileTypeOption: [], // 上传文件类型数据选项,
            // colOption, // 附件表头
            dialogUpload: false, // 旧逻辑代码，指派签署人弹框
            dialogUploadNew: false, // 上传附件弹框
            isShowStampUnit: false, // 是否展示签署单位
            prjParams: {}, // 页面路由参数集
            dicLists: {}, // 字典数据集合
            prjData: {}, // 嵌套数据数据
            fileObj: {}, // 预览文件地址
            dialogFileView: false, // 预览弹框
            dialogEdit: false, // 编辑弹框
            isUploadBtn: false, // 是否点击上传按钮
            dialogTitle: '指派签署人', // 弹框标题
            pageHeight: 200, // 附件列表页面默认高度
            // 列表按钮配置枚举
            btnEnum: {
                'A': btnOptionA,
                'B': btnOptionB,
                'C': btnOptionC,
                'D': btnOptionD,
                'E': btnOptionE,
                'F': btnOptionF
            },
            columnEnum: {
                'A': colOptionA,
                'B': colOptionB,
                'C': colOptionA,
                'D': colOptionB,
                'E': colOptionA,
                'F': colOptionA
            },
            editSrc: '', // 编辑嵌套页面地址
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            assignDisable: false,
            dialogEditTitle: '编辑',
            dialogEditHeight: '500',
            wpsToken: '',
            previewObj:{},
            tableForm: {
              prjStage: '', // 选择项目阶段
              nodeId: '', // 项目节点
              prjCode:''
            },
            selectArray:[]
        }
    },
    async created() {
        const {
            prjId,
            nodeId = '0',
            prjType = '0',
            buildModes = '0',
            towerType = '0',
            roomType = '0',
            prjStage,
            orgId,
            projectId = '',
            // fileSupplierCode = '',
            isChange = '0',
            operateType = '1',
            btnConfig = 'A',
            processId = '',
            businessMajor = '',
            businessType = '',
            showPrjCode,
        } = getQueryObject()
        let buildModesNew = buildModes === 'null' || !buildModes ? '0' : buildModes
        let showPrjCodeNew = showPrjCode === 'null' || !showPrjCode ? '1' : showPrjCode
        if (prjType === 'Z') {
            await queryBuildModesApi({
                prjId,
                prjType
            }).then((res) => {
                if (+res.code === 200) {
                    if (res.data.projectAttribution === '01') {
                        buildModesNew = '01'
                    } else if (res.data.projectAttribution === '02') {
                        buildModesNew = '09'
                    } else {
                        console.log('[]')
                    }
                }
            })
        }
        this.tableForm.prjStage=prjStage; //初始时候，默认展示当前阶段
        this.prjParams = {
            prjId, // 项目id
            prjType, // 项目类型
            nodeId, // 当前节点ID
            buildModes: buildModesNew, // 建设模式
            towerType, // 塔类型
            roomType, // 室分类型
            prjStage, // 项目阶段
            isChange, // 上传方式 0:正常上传的,1:整改的,2:继承的
            operateType, // 操作类型，1:新增，2:补传
            btnConfig, // 列表按钮配置
            processId, // 工序id
            orgId,
            projectId,
            showPrjCode:showPrjCodeNew,
            businessMajor: this.getBusinessMajor(businessMajor),
            businessType:this.getBusinessType(businessType),
        }
        console.log(1111111, this.prjParams)
        if (btnConfig !== 'B') {
            this.getPrjFileType()
            // if(prjStage==='E'||prjStage==='F'){
            //     await this.accGenerationElectron();
            // }
        }
        await this.getDictData()
        await this.getPrjStage()
        await this.getToken()
        await this.querySuffix()
        await this.getSingleInfo()
        await this.getNodeInfo(prjStage)
    },
    mounted() {
        window.parent.postMessage({ height: this.$refs.attachmentListRef.clientHeight, type: 'attachment' }, this.$fixIframeArr())
    },
    methods: {
        // 获取到单项工程下拉列表数据
        getSingleInfo() {
          console.log(this.prjParams)
          const params = {
            prjId: this.prjParams.prjId,
            nodeId: this.prjParams.nodeId,
            prjStage: this.prjParams.prjStage
          }
          querySingleInfo(params).then((res) => {
            if (+res.code !== 200) {
              return Promise.reject(res)
            }
            this.selectArray = res.data
            if(this.selectArray.length > 0 && +this.prjParams.showPrjCode === 1){
              this.tableForm.prjCode=this.selectArray[0].prjCode
              this.columnEnum[this.prjParams.btnConfig].splice(2,0,{
                label: '项目编码', width: '180', prop: 'prjCode'
              })
            }
          }).finally(()=>{
            this.doSearch();
          })
        },
        // 改变项目阶段事件
        async changePrjPhase() {
          this.tableForm.prjStage ? await this.getNodeInfo(this.tableForm.prjStage) : this.$set(this.dicLists, 'ATT_PRO_NODE', [])
          this.tableForm.nodeId = ''
          await this.doSearch();
        },
        // 获取项目节点字典
        async getNodeInfo(val) {
          const projectId = this.prjParams.projectId || this.prjParams.prjId
          const res = await getNodeInfoApi({ prjId: projectId, prjStage: val ?? '' })
          this.$set(this.dicLists, 'ATT_PRO_NODE', res.data)
        },
        // 改变项目节点事件
        async changePrjNode() {
          //刷新页面
          await this.doSearch();
        },
        // 改变项目编码
        async changePrjCode(){
          await this.doSearch();
        },
        querySuffix() {
            querySuffix().then((res) => {
                if (+res.code === 200) {
                    this.previewObj = res.data
                }
            })
        },
        getBusinessMajor(businessMajor){
            return businessMajor === 'null' || !businessMajor || businessMajor === 'undefined'? '' : businessMajor;
        },
        getBusinessType(businessType){
            return businessType === 'null' || !businessType || businessType === 'undefined' ? '' : businessType;
        },
        // 生成数据
        // async accGenerationElectron(){
        //     const params={
        //         prjId:this.prjParams.prjId,
        //         nodeId:this.prjParams.nodeId,
        //         prjType:this.prjParams.prjType,
        //     }
        //     await acceGenerationElectron(params).then(res => {
        //         console.log(res)
        //         // if (+res.code !== 200) return Promise.reject(res)
        //     })
        // },
        getBusinessStatus(){
          return (this.prjParams.prjStage === 'E' || this.prjParams.prjStage === 'F') && this.prjParams.businessMajor === '03'
        },
        getNodeFlag(){
            if(this.tableForm.prjStage === this.prjParams.prjStage){
               if( this.tableForm.nodeId ){
                 return {
                   nodeId:this.tableForm.nodeId,
                   flagNum:'2'
                 }
               }else{
                 return {
                   nodeId:this.prjParams.nodeId,
                   flagNum:'1'
                 }
               }
            }else{
              return {
                nodeId:this.tableForm.nodeId,
                flagNum:'2'
              }
            }
        },
        // 查看数据
        doSearch(item) {
            let params = {
                prjId: this.prjParams.prjId,
                prjStage: this.tableForm.prjStage,
                nodeId: this.getNodeFlag().nodeId,
                flagNum: this.getNodeFlag().flagNum,
                prjCode: this.tableForm.prjCode,
                prjType: this.prjParams.prjType,
                // buildModes: this.prjParams.buildModes,
                // towerType: this.prjParams.towerType,
                // roomType: this.prjParams.roomType,
                processId: this.prjParams.processId,
                // uploadEmpId: '1', //人员id字段，可以不传
                // prjNodeId: this.prjParams.prjStage === 'E' ? this.prjParams.nodeId : '', //实施阶段当时单独处理的信息 加了个代办进去的页面传入1
                isWaitFlag: this.prjParams.btnConfig === 'B' || this.prjParams.btnConfig === 'D' ? '01' : '',
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                // businessMajor: this.getBusinessStatus() ? this.prjParams.businessMajor : '',
                // businessType: this.getBusinessStatus() ? this.prjParams.businessType : '',
            }
            queryDocInfo(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                console.log(res, '附件信息')
                this.tableData = res.data.records
                this.pageParam.total = res.data?.total || 0
                this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
                this.$nextTick(() => {
                    const h = this.$refs.attachmentListRef.clientHeight
                    this.pageHeight = h < 220 ? 220 : h
                    window.parent.postMessage({ height: this.pageHeight , type: 'attachment' }, this.$fixIframeArr())
                    console.log(h, this.pageHeight, 'this.pageHeight-true')
                })
            })
        },
        // 当父组件接收到了子组件this.$emit的通知后就会执行这个方法来接收子组件点击传递过来的数据
        btnClick(fun, row) {
            this[fun](row)
        },
        getToken() {
            getWPSToken().then((res) => {
                if (+res.code === 200) {
                    this.wpsToken = res.data
                }
            })
        },
        // 点击指派签署人按钮
        assign(row) {
            console.log('row', row)
            const IsAssignFLag = row.some(item => item.isSignature === '1' && !['1'].includes(item.signatureStatus))
            if (IsAssignFLag) {
                return msgInfoEl({
                    type: 'info',
                    message: '是电子签章且签章状态为待指派时支持指派签署人'
                })
            }
            const isAssign = row.some(item => item.nodeId !== row[0].nodeId)
            if (isAssign) {
                return msgInfoEl({
                    type: 'info',
                    message: '不同节点不支持指派签署人'
                })
            }
            const assignOpen = row.some(item => item.fileSource === '0' && item.isSignature === '0')
            if (assignOpen) {
                return msgInfoEl({
                    type: 'info',
                    message: '手动上传且电子签章为否时的文件不支持指派签署人'
                })
            }
            this.dialogTitle = '指派签署人'
            this.isUploadBtn = false
            this.dialogUpload = true
            this.isShowStampUnit = true
            this.prjData = {
                nodeId: row[0].nodeId,
                docType: row.map(item => item.docTypeCode).join(),
                proStage: row[0].prjStage,
                prjId: this.prjParams.prjId,
                fileId: row.map(item => item.fileId).join(),
                fileSource: row.map(item => item.fileSource).join()
            }
            this.dialogEl('dialogUploadRef')
        },
        // 上传附件按钮
        upload() {
            console.log('this.prjFileTypeOption', this.prjFileTypeOption)
            if (this.prjFileTypeOption.length > 0) {
                this.isUploadBtn = true
                this.dialogUploadNew = true
                this.dialogTitle = '上传附件'
                this.dialogEl('dialogUploadNewRef')
            } else {
                msgInfoEl({
                    type: 'info',
                    message: '当前流程节点无可上传的附件信息，请联系维护人员增加上传需求'
                })
            }
        },
        // 上传附件中-签署人改变事件
        changeSignatory(val1, val2) {
            this.isShowStampUnit = val1
            this.prjData = {
                docType: val2,
                proStage: this.prjParams.prjStage,
                prjId: this.prjParams.prjId
            }
        },
        // 上传事件
        // batchUploadClick() {
        //     const uploadFormData = this.isUploadBtn ? this.$refs.uploadAttachRef.uploadForm : {}
        //     // const signatoryData = this.$refs.chooseSignatoryRef.getSelectionSignatory
        //     // 备注：uploadForm.isEleSign === '0' => 附件上传; uploadForm.isEleSign === '1' => 电子签章上传
        //     if (uploadFormData.isEleSign === '0') {
        //         // 附件上传
        //         this.attachmentUpload(uploadFormData)
        //     } else {
        //         this.isUploadBtn ? this.eleSignUpload(uploadFormData) : this.assignSignatory(this.prjData, this.prjData.fileId)
        //     }
        //
        // },
        // 指派签署人提交
        assignSignatorysubmit() {
            this.assignSignatory(this.prjData, this.prjData.fileId)
        },
        // 电子签章上传接口  逻辑修改，之前在上传中指定电子签章，目前可能用不到
        eleSignUpload(uploadForm) {
            console.log(uploadForm, 'uploadFormuploadFormuploadForm')
            const {
                prjId, // 项目id
                nodeId, // 流程id
                prjStage, // 项目阶段
                isChange, // 上传方式 0:正常上传的,1:整改的,2:继承的
                prjType,
                buildModes,
                towerType,
                roomType,
                operateType, // 操作类型，1:新增，2:补传
                processId // 工序id
            } = this.prjParams
            if (!uploadForm.fileList.length) {
                return msgInfoEl({
                    type: 'info',
                    message: '请上传文件'
                })
            }
            const params = {
                file: uploadForm.fileList[0].raw, // 文件
                docFileType: uploadForm.docTypeCode, // 文件类型
                prjId, // 项目id
                activityId: nodeId, // 流程id
                prjType,
                buildModes,
                towerType,
                roomType,
                prjStage, // 项目阶段
                isChange, // 上传方式 0:正常上传的,1:整改的,2:继承的
                operateType, // 操作类型，1:新增，2:补传
                operateSystem: '0', // 操作系统 0:PMS,1:施工管理
                oldDocId: '',
                isReplaceFlag: 'N',
                supplementType: this.$route.meta.supplementType,
                processId
            }
            const formData = new FormData()
            Object.keys(params).forEach(key =>
                formData.append(key, params[key])
            )
            uploadSignInfoApi(formData).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                if (this.isShowStampUnit) {
                    this.assignSignatory({
                        nodeId: this.prjParams.nodeId,
                        proStage: this.prjParams.prjStage,
                        docType: uploadForm.docTypeCode,
                        fileSource: ''
                    }, res.data)
                } else {
                    this.dialogUpload = false
                    this.doSearch()
                    this.dialogClosed()
                    msgInfoEl({
                        type: 'success',
                        message: res.message
                    })
                }
            })
        },
        // 指派签署人接口
        assignSignatory(uploadForm, oldDocId) {
            const params = {
                docFileType: uploadForm.docType,
                prjId: this.prjParams.prjId, // 项目id
                activityId: uploadForm.nodeId,
                prjStage: uploadForm.proStage,
                oldDocId,
                fileSource: uploadForm.fileSource
            }
            this.assignDisable = true
            assignSignatoryApi(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                this.dialogUpload = false
                this.doSearch()
                this.dialogClosed()
                msgInfoEl({
                    type: 'success',
                    message: res.message
                })
                console.log('指派签署人成功')
            }).finally(() => {
                this.assignDisable = false
            })
        },
        // 下载
        download(row) {
            console.log(row, '下载--row')
            const fileDownloadNo = row.find(item => item.fileId === '' || item.fileId === null || item.fileId === undefined) || {}
            if (JSON.stringify(fileDownloadNo) !== '{}') {
                return msgInfoEl({
                    type: 'info',
                    message: `当前选择范围中存在未上传文件，请上传或取消勾选该文件再进行下载`
                })
            }
            const fileName = row.length > 1 ? '附件信息.zip' : row[0].fileName
            // 单个文件下载时的参数
            const params = {
                fileId: row[0].fileId,
                fileName: row[0].fileName
            }
            // 多个文件下载时的参数
            const batchParams = row.map(item => ({
                fileId: item.fileId,
                fileName: item.fileName
            }))
            if (row.length > 1) {
                // mulDownload(row, fileName)
                // 批量下载
                batchDownloadApi({ fileMap: batchParams }).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            } else {
                // singleDownload(row, fileName)
                // 单个文件下载
                downloadApi(params).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            }
        },
        // 删除附件按钮  代码合并后 增加nodeId
        delete(row) {
            const isDel = row.some(item => item.isSignature !== '1' || ['1','3', '4', '5', '9'].includes(item.signatureStatus))
            if (!isDel) {
                return msgInfoEl({
                    type: 'info',
                    message: '文件为电子签章时，仅支持签署状态为待指派、拒签、作废、已签署完成、转换失败时才能删除'
                })
            }
            const isRel = row.some(item => item.fileSource !== '0')
            if (isRel) {
                return msgInfoEl({
                    type: 'info',
                    message: '仅支持文件获取方式为手动上传的文件'
                })
            }
            const isRemove = row.some(item => item.nodeId !== row[0].nodeId)
            if (isRemove) {
                return msgInfoEl({
                    type: 'info',
                    message: '不同节点不支持批量删除'
                })
            }
            const params = [];
            row.forEach((item)=>{
                if(item.fileId){
                    params.push({
                        fileId:item.fileId,
                        prjId:item.prjId,
                        supplementType:this.$route.meta.supplementType,
                        nodeId: this.prjParams.nodeId,
                    })
                }
            })
            if(params.length > 0){
                this.deleteConfirm(params);
            }else{
                return msgInfoEl({
                    type: 'error',
                    message: '没有文件可进行删除'
                })
            }
        },
        deleteConfirm(params){
            const contentBody = window.top.document.body
            this.$confirm('确认删除所选数据, 是否继续?', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                closeOnClickModal: false
            }).then(() => {
                batchDeleteApi(params).then(res => {
                    if (+res.code !== 200) {
                        return Promise.reject(res)
                    }
                    this.doSearch({
                        page: this.pageParam.pageNum,
                        limit: this.pageParam.pageSize
                    })
                    this.$refs.myTableRef.clearSelection()
                    // this.$refs.myTableRef.toggleRowSelection(row)
                    enableScroll(contentBody)
                    msgInfoEl({
                        type: 'success',
                        message: res.message
                    })
                })
            }).catch(() => {
                enableScroll(contentBody)
                console.log('取消删除了')
            })
            // el-message-box__wrapper
            // 将弹框挂载在最外层
            this.$nextTick(() => {
                const msgBox = document.querySelector('.el-message-box__wrapper')
                contentBody.appendChild(msgBox)
                disableScroll(contentBody)
            })
        },
        getUserId(){
            let str='';
            if(sessionStorage.getItem('SET_LOGINDATA')){
              str = JSON.parse(sessionStorage.getItem('SET_LOGINDATA')).staffId
            }else if(sessionStorage.getItem('userInfo')){
              str = JSON.parse(sessionStorage.getItem('userInfo')).staffId
            }else{
              console.log('')
            }
            console.log('str',str)
            return str;
        },
        // 点击文件名称-预览
        async preview(row) {
            if (row.isSignature === '1') {
                this.getSignFlowDocUrls(row.fileViewId)
                return
            } else {
                const types = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
                const previewArray = Object.keys(this.previewObj);
                console.log(111,previewArray,this.previewObj,this.previewObj[types])
                if (previewArray.includes(types)) {
                    const params = {
                        fileId: row.fileId,
                        type: this.previewObj[types],
                        userId: this.getUserId(),
                        token: this.wpsToken
                    }
                    getPreviewFile(params).then((res) => {
                        if (+res.code === 200 && res.data) {
                            window.open(res.data, '_blank')
                        }
                    })
                } else {
                    return msgInfoEl({
                        type: 'info',
                        message: `所选文件不支持预览`
                    })
                }
            }
            // let res = {}
            // const params = {
            //     fileId: row.fileId,
            //     fileName: row.fileName
            // }
            // await downloadApi(params).then(r => {
            //     res = r
            // })
            // const blob = new Blob([res.data], { type: 'application/pdf;charset-UTF-8' })
            // const url = window.URL.createObjectURL(blob)
            // row.filePath = url
            // this.fileObj = {}
            // if (!row.filePath) {
            //     return msgInfoEl({
            //         type: 'info',
            //         message: `所选${row.fileName}文件不支持预览`
            //     })
            // }
            // const types = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
            // if (['word', 'docx', 'excel', 'xlsx'].includes(types)) {
            //     console.log(types, '12')
            //     window.open(this.$router.resolve({
            //         name: 'FilePreview',
            //         query: {
            //             type: types,
            //             fileSrc: row.filePath
            //         }
            //     }).href, '_blank')
            //     return
            // }
            // if (['pdf'].includes(types)) {
            //     window.open(row.filePath, '_blank')
            //     return
            // }
            // if (['pptx', 'ppt', 'xls', 'doc'].includes(types)) {
            //     // window.open(`${process.env.VUE_APP_BASE_API}preview/onlinePreview?url=${encodeURIComponent(Base64.encode(row.filePath))}`, '_blank')
            //     return msgInfoEl({
            //         type: 'info',
            //         message: `所选文件不支持预览`
            //     })
            // }
            // if (['jpg', 'png', 'jpeg', 'bmp', 'mp3', 'mp4', 'webm', 'ogg', 'aac', 'wav'].includes(types)) {
            //     this.fileObj = {
            //         type: types,
            //         fileSrc: row.filePath
            //     }
            //     this.dialogFileView = true
            //     this.dialogEl('dialogViewRef')
            // } else if (['txt'].includes(types)) {
            //     axios.get(row.filePath, {
            //         responseType: 'blob',
            //         transformResponse: [
            //             async function(data) {
            //                 // txt转码
            //                 return await new Promise((resolve) => {
            //                     const reader = new FileReader()
            //                     reader.readAsText(data, 'UTF-8') // GBK UTF-8
            //                     reader.onload = () => {
            //                         resolve(reader.result)
            //                     }
            //                 })
            //             }
            //         ]
            //     }).then(_res => {
            //         _res.data.then((data) => {
            //             this.fileObj = {
            //                 type: types,
            //                 fileSrc: data
            //             }
            //         })
            //     })
            //     this.dialogFileView = true
            //     this.dialogEl('dialogViewRef')
            // } else {
            //     msgInfoEl({
            //         type: 'info',
            //         message: '不支持预览此文件'
            //     })
            // }
            // console.log(row, types, '预览')
        },
        // 电子签章预览
        getSignFlowDocUrls(id) {
            getSignFlowDocUrlsApi({ id }).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                if (res.data) {
                    // window.open(res.data, '_blank')
                    axios.get(res.data, {
                        responseType: 'blob',
                        cache: true,
                        headers: {
                            'Content-Disposition': 'inline'
                        }
                    }).then(r => {
                        const blob = new Blob([r.data], { type: 'application/pdf;charset-UTF-8' })
                        // const blob = new Blob([r.data], { type: r.headers['content-type'] })
                        const url = window.URL.createObjectURL(blob)
                        window.open(url, '_blank')
                        URL.revokeObjectURL(url) // 释放内存
                    })
                }
            })
        },
        // 列表编辑操作
        edit(row) {
            console.log('测试一下')
            if (['0', '1'].includes(row[0].fileSource)) {
                return msgInfoEl({
                    type: 'info',
                    // message: '当前仅支持对文件获取方式为“系统生成/手动编辑”进行编辑操作'
                    message: '仅支持对文件获取方式为“系统生成/手动编辑”进行编辑'
                })
            }
            // 实施阶段跳降门页面，其余阶段暂时不跳
            if (this.prjParams.prjStage === 'E') {
                if (['single_project_ys_103', 'shishi_nztsgxc01'].includes(row[0].nodeId)) {
                    this.jumpEditZr(row)
                } else {
                    this.editCheck(row);
                }
            } else if (this.prjParams.prjStage === 'F') {
                this.jumpEditZr(row)
            } else {
                return msgInfoEl({
                    type: 'info',
                    message: '当前附件非需编辑的电子化文档，请选择其他附件'
                })
            }
        },
        editCheck(row){
            if(row[0].nodeId === this.prjParams.nodeId){
                this.editSrc = `${process.env.VUE_APP_JIANGMEN_URL}designDisclosureCover?docType=${row[0].docTypeCode}&fileId=${row[0].fileId}&prjId=${this.prjParams.prjId}`
                this.dialogEdit = true
                window.addEventListener('message', this.handleMessage)
                // this.dialogEl('dialogEditRef')
                // 将弹框挂载在最外层
                const contentBody = window.top.document.body
                this.$nextTick(() => {
                    const dialogModal = document.querySelector('.v-modal')
                    const elBody = this.$refs.dialogEditRef.$el
                    dialogModal.style.zIndex = 4000
                    elBody.style.zIndex = 4001
                    contentBody.appendChild(elBody)
                    contentBody.appendChild(dialogModal)
                    disableScroll(contentBody)
                })
            }else{
                return msgInfoEl({
                    type: 'info',
                    message: '当前附件非需编辑的电子化文档，请选择其他附件'
                })
            }
        },
        jumpEditZr(row) {
            const params = {
                prjId: row[0].prjId,
                docType: row[0].docTypeCode
            }
            checkFileEditing(params).then(res => {
                if (+res.code === 200) {
                    this.editSrc = `${process.env.VUE_APP_ZHONGRUAN_URL}electronDocCreate?docType=${row[0].docTypeCode}&prjId=${row[0].prjId}&nodeId=${row[0].nodeId}&prjType=${this.prjParams.prjType}`
                    // this.editSrc = `http://localhost:9528/electronDocCreate?docType=D45&prjId=30016693&nodeId=acceptance_v103&prjType=A`
                    this.dialogEdit = true
                    window.addEventListener('message', this.handleMessage)
                    // 将弹框挂载在最外层
                    const contentBody = window.top.document.body
                    this.$nextTick(() => {
                        const dialogModal = document.querySelector('.v-modal')
                        const elBody = this.$refs.dialogEditRef.$el
                        dialogModal.style.zIndex = 4000
                        elBody.style.zIndex = 4001
                        contentBody.appendChild(elBody)
                        contentBody.appendChild(dialogModal)
                        disableScroll(contentBody)
                    })
                    if (row[0].docTypeCode === 'D44') {
                        this.dialogEditTitle = '内部验收证书'
                    } else if (row[0].docTypeCode === 'D45') {
                        this.dialogEditTitle = '项目验收报告'
                    } else {
                        this.dialogEditTitle = '编辑'
                    }
                }
            })
        },
        // iframe加载完成事件
        handleMessage(event) {
            console.log(event.data, 'event123')
            const base_url = ''
            if (event.origin === base_url) {
                return
            }
            // if (event.data.data) {
            //     this.dialogEdit = false
            //     this.dialogClosed()
            //     msgInfoEl({
            //         type: 'success',
            //         message: '操作成功！'
            //     })
            //     this.doSearch({
            //         page: this.pageParam.pageNum,
            //         limit: this.pageParam.pageSize
            //     })
            //     return
            // }
            this.iframeHeight = event.data.height + ''
            this.$refs.signatoryPreRef.style.height = event.data.height + 'px'
            // if (event.data.type === 'electronEditTitle') {
            //     this.dialogEditTitle = event.data.data
            // }else if (event.data.type === 'electronDocHeight') {
            //     this.dialogEditHeight = event.data.height
            // }else{
            //     this.dialogEditTitle = '编辑'
            // }
        },
        // 关闭编辑弹框
        editClose() {
            this.dialogClosed()
            this.doSearch({
                page: this.pageParam.pageNum,
                limit: this.pageParam.pageSize
            })
        },
        // 获取附件允许上传文件类型数据
        getPrjFileType() {
            const {
                prjType, // 项目类型
                nodeId, // 当前节点ID
                buildModes, // 建设模式
                towerType, // 塔类型
                orgId,
                roomType // 室分类型
            } = this.prjParams
            const params = {
                prjType, // 项目类型
                nodeId, // 当前节点ID
                buildModes, // 建设模式
                towerType, // 塔类型
                roomType, // 室分类型
                orgId,
                businessMajor: this.getBusinessStatus() ? this.prjParams.businessMajor : '',
                businessType: this.getBusinessStatus() ? this.prjParams.businessType : '',
            }
            getPrjFileTypeApi(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                this.prjFileTypeOption = res.data
            })
        },
        // 获取下拉框字典数据
        async getDictData() {
            const arr = ['SIGN_STATE2']
            const promises = arr.map(item => getDropdownData(item))
            const results = await Promise.all(promises)
            arr.forEach((item, i) => {
                this.$set(this.dicLists, item, results[i].data ?? [])
            })
        },
        // 获取项目阶段字典
        async getPrjStage() {
            const res = await getPrjStageApi()
            const stageData = res.data.map(item => ({
                dictId: item.key,
                dictName: item.value
            }))
            this.$set(this.dicLists, 'PRO_STAGE', stageData)
        },
        // 将弹框挂载在最外层
        dialogEl(refName) {
            // 将弹框挂载在最外层
            const contentBody = window.top.document.body
            this.$nextTick(() => {
                const dialogModal = document.querySelector('.v-modal')
                contentBody.appendChild(this.$refs[refName].$el)
                contentBody.appendChild(dialogModal)
                disableScroll(contentBody)
            })
        },
        // 关闭弹框
        dialogClosed() {
            const contentBody = window.top.document.body
            enableScroll(contentBody)
            this.$nextTick(() => {
                const _message = contentBody.getElementsByClassName('el-message')
                if (_message && _message.length > 0) {
                    for (let i = 0; i < _message.length; i++) {
                        contentBody.removeChild(_message[i])
                        this.dialogClosed()
                    }
                } else {
                    this.dialogEdit = false
                }
            })
        },
        // 数字图纸
        digital() {
            const projectId = this.prjParams.projectId || this.prjParams.prjId
            getDigitalDrawingsUrl(projectId).then(res => {
                if (res.code === '200') {
                    window.open(res.data.jumpUrl)
                }
            })
        },
        // 工程资料全览
        fullView() {
            const url = `${process.env.VUE_APP_ZHONGRUAN_URL}attachmentFullView?prjId=${this.prjParams.prjId}&prjStage=${this.prjParams.prjStage}`
            window.open(url)
        },
        // 补传
        attachmentPass() {
            const url = `${process.env.VUE_APP_ZHONGRUAN_URL}attachmentPass?prjId=${this.prjParams.prjId}`
            window.open(url)
        },
        // 开始上传
        startUpload() {
            this.$refs.uploadAttachRef.startUpload()
        },
        dialogUploadClosed() {
            this.dialogUploadNew = false
            this.dialogClosed()
            this.doSearch()
        }
    }
}
</script>

<style lang="scss" scoped>
.attachmentList {
    height: auto;
}
.pms-details {
  //margin-right: 10px;
  display: flex;
  width: auto;
  justify-content: flex-start;
  flex-wrap: wrap;
  .el-form-item {
    width: auto;
  }
}

.el-button--text {
    color: #02A7F0;
}

.el-button--primary {
    color: #fff;
}

.el-button--mini {
    color: #fff;
}

.signatoryBody {
    min-height: 170px;
    max-height: 420px;
    overflow-y: auto;
    overflow-x: hidden;
}

.signatoryPre {
    max-height: 70vh;
    overflow-y: auto;
    overflow-x: hidden;
}

.el-collapse {
    margin-bottom: 20px;
}

.el-collapse-item {
    box-shadow: 0px 0px 6px 0px rgba(191, 192, 192, 0.52);
    /* 调整各个item之间的距离为20px */
    /* border: 1px; */
}

.el-collapse-item__wrap {
    padding: 0 20px;
    /* 为el-collapse-item的内容添加20像素的padding */
}

.el-collapse-item__header {
    padding-left: 20px;
    font-size: 14px;
    color: #333333;
    letter-spacing: 0;
    font-weight: 600;
}

.item_icon {
    width: 6px;
    background: rgb(235, 75, 75);
    height: 15px;
    margin-right: 10px;
    border-radius: 10px;
}

.content-box {
    width: 100%;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 400;
    line-height: 25px;
}

.headerLeft {
    font-size: 14px;

    .headerLeftTitle {
        color: #D9001B;
    }
}

::v-deep .el-select-dropdown__wrap{
  max-height: 140px !important;
}
</style>
